package edu.ctbu.insurance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.ctbu.insurance.bean.User;
import edu.ctbu.insurance.service.UserService;
import edu.ctbu.insurance.service.userEmail.EmailService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author djl
 * @since 2024-06-28
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    /**
     * 查询user表所有信息
     * @return user表所有信息
     */
    @RequestMapping("/getAllUser")
    public List<User> getAllUer(){
        return userService.list();
    }

    @RequestMapping("/createUser")
    public String createUser(String userName, String userPwd) {
        User user = new User();
        user.setUserName(userName);
        user.setUserPwd(userPwd);
        user.setUserAccount(userService.createUser());

        userService.save(user);

        //返回生成的账号
        return user.getUserAccount();
    }


    /**
     * 更新个人信息
     */
    @RequestMapping("/updateUser")
    public void updateUser(User user, MultipartFile upFile) throws IOException {
        System.out.println("1");
        if (upFile == null || upFile.isEmpty()) {
            System.out.println("1");
            userService.updateById(user);
        } else {
            System.out.println("1");
            if (userService.getById(user.getId()).getUserHeadImg() != null) {
                System.out.println("1");
                // 删除旧头像
                File deleteFile = new File("D:/Applications/IntelliJ IDEA 2024.1/insurance-management-system-v0.1/insurance-management-system-front-v0.1/public/user-head-img/" +
                        userService.getById(user.getId()).getUserHeadImg());
                deleteFile.delete();

                User user1 = new User();
                //删除数据库中的头像信息
                user1.setId(user.getId());
                user1.setUserAccount(user.getUserAccount());
                user1.setUserName(user.getUserName());
                user1.setUserPwd(user.getUserPwd());
                user1.setUserCompany(user.getUserCompany());
                user1.setUserSex(user.getUserSex());
                user1.setUserEmail(user.getUserEmail());
                user1.setUserPhoneNumber(user.getUserPhoneNumber());
                user1.setUserIntroduction(user.getUserIntroduction());
                user1.setUserHeadImg("");
                user1.setUserBirthday(user.getUserBirthday());
                user1.setUserAddress(user.getUserAddress());
                user1.setUserRole(user.getUserRole());

                userService.updateById(user1);
            }
            String oldFileName = upFile.getOriginalFilename();
            String filenameType = oldFileName.substring(oldFileName.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + filenameType;
            // 这里的路径是本机电脑当前前端项目的绝对路径，使用时请更改到项目中的对应位置
            File file = new File("D:/Applications/IntelliJ IDEA 2024.1/insurance-management-system-v0.1/insurance-management-system-front-v0.1/public/user-head-img/"+fileName);
            upFile.transferTo(file);
            user.setUserHeadImg(fileName);

            userService.updateById(user);
        }
    }

    @RequestMapping("/login")
    public String login(String userAccount, String userPwd, HttpSession session) {
        if (userService.login(userAccount, userPwd)) {
            //session中存入用户信息
            session.setAttribute("userAccount", userAccount);
            return "success";
        } else {
            return "error";
        }
    }

    @RequestMapping("/getSession")
    public User getSession(HttpSession session) {
        String userAccount = (String) session.getAttribute("userAccount");
        //根据userAccount查询出userName返回
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_account",userAccount);
        User one = userService.getOne(queryWrapper);
        return one;
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "ok";
    }

    @RequestMapping("/sendEmail")
    public String sendEmail(String email, HttpSession httpSession) {
        if (userService.getUserByEmail(email).isEmpty()) {
            return "none";
        }

        return emailService.sendEmail(email, httpSession);
    }

    @RequestMapping("/emailLogin")
    public User emailLogin(String emailCode, HttpSession httpSession) {
        String email = emailService.emailLogin(emailCode, httpSession);
        if (email.equals("error")) {
            User user = new User();
            user.setUserAccount("error");
            return user;
        } else {
            return userService.getUserByEmail(email).get(0);
        }
    }
}
